<template>
    <div>
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>添加入库单</span>
                </div>
            </template>

            <el-form :model="formData" ref="form" label-width="120px" :rules="rules">
                <!-- 第一行：入库单基本信息 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="入库单号" prop="inboundCode">
                            <div class="code-input-container">
                                <el-input placeholder="请输入入库单编号" v-model="formData.inboundCode"
                                    :disabled="autoGenerate">
                                </el-input>
                                <div class="switch-container">
                                    <el-switch v-model="autoGenerate" @change="handleAutoGenerateChange" />
                                    <span class="switch-label">自动生成</span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库名称" prop="inboundName">
                            <el-input placeholder="请输入入库名称" v-model="formData.inboundName">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第二行：计划信息 -->
                <el-row :gutter="20">
                    <el-col :span="8" :offset="0">
                        <el-form-item label="选择计划">
                            <el-input style="width: 350px; margin-right: 10px;" v-model="formData.planId"
                                placeholder="请选择计划" disabled></el-input>
                            <el-button type="primary" @click="showPlanModal">选择计划</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="仓库ID" prop="warehouseId">
                            <template #default>
                                <el-select v-model="formData.warehouseId" placeholder="请选择仓库" style="width: 100%">
                                    <el-option v-for="item in warehouseOptions" :key="item.warehouseId"
                                        :label="item.warehouseName" :value="item.warehouseId"></el-option>
                                </el-select>
                            </template>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第三行：批次和人员信息 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="批次号" prop="batchNo">
                            <el-input placeholder="请输入批次号" v-model="formData.batchNo">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库员ID" prop="operatorId">
                            <template #default>
                                <el-select v-model="formData.operatorId" placeholder="请选择报工人员">
                                    <el-option v-for="item in users" :key="item.username" :label="item.nickname"
                                        :value="item.username" />
                                </el-select>
                            </template>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="质检员ID" prop="checkId">
                            <template #default>
                                <el-select v-model="formData.checkId" placeholder="请选择报工人员">
                                    <el-option v-for="item in users" :key="item.username" :label="item.nickname"
                                        :value="item.username" />
                                </el-select>
                            </template>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第四行：数量信息 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="计划数量" prop="totalQuantity">
                            <el-input-number v-model="formData.totalQuantity" :min="0" :precision="2" :step="0.1"
                                controls-position="right" style="width: 100%" placeholder="请输入计划数量">
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="实际数量" prop="actualQuantity">
                            <el-input-number v-model="formData.actualQuantity" :min="0" :precision="2" :step="0.1"
                                controls-position="right" style="width: 100%" placeholder="请输入实际数量" :max="formData.totalQuantity">
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库状态" prop="inboundStatus">
                            <el-select v-model="formData.inboundStatus" placeholder="请选择状态" style="width: 100%">
                                <el-option label="未开始" :value="0"></el-option>
                                <el-option label="已完成" :value="1"></el-option>
                                <el-option label="已取消" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 第五行：金额信息 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="入库日期" prop="createTime">
                            <el-date-picker v-model="formData.createTime" type="datetime" placeholder="选择入库日期"
                                style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 产品信息-->
                <el-divider content-position="left">产品信息</el-divider>


                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="产品编号">
                            <el-input v-model="formData.productId" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="产品名称">
                            <el-input v-model="formData.materialName" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12" :offset="0">
                        <el-form-item label="规格型号">
                            <el-input v-model="formData.specifications" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <el-form-item label="单位">
                            <el-input v-model="formData.unit" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 操作按钮 -->
                <el-form-item class="form-actions">
                    <el-button type="primary" @click="onSubmit">立即创建</el-button>
                    <el-button @click="resetForm">重置</el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-form-item>
            </el-form>

            <el-dialog v-model="orderDialogVisible" title="选择计划" width="70%">
                <el-table :data="plans" style="width: 100%;">
                    <el-table-column label="计划编号" prop="planId" width="120" />
                    <el-table-column label="计划名称" prop="planName" width="120" />
                    <el-table-column label="产品编号" prop="materialId" width="120" />
                    <el-table-column label="产品名称" prop="materialName" width="120" />
                    <el-table-column label="规格型号" prop="specificationsAndModels" width="120" />
                    <el-table-column label="单位" prop="unit" width="120" />
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button @click="selectPlan(scope.row)">选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import { useRouter } from 'vue-router'

const router = useRouter()
const emits = defineEmits(['ref-table'])

const users = ref([])
onMounted(async () => {
    request.post('/system/user/list', { size: 1000 }).then(res => {
        users.value = res.data.records
    })
    request({
        url: '/warehouse/tree',
        method: 'get'
    }).then(res => {
        console.log(res.data)
        warehouseOptions.value = res.data
    })
})

// 是否自动生成入库单号
let autoGenerate = ref(true)

// 表单数据
let formData = ref({
})

// 表单验证规则
const rules = reactive({
    inboundName: [
        { required: true, message: '请输入入库名称', trigger: 'blur' }
    ],
    planId: [
        { required: true, message: '请输入计划ID', trigger: 'blur' }
    ],
    warehouseId: [
        { required: true, message: '请输入仓库ID', trigger: 'blur' }
    ],
    totalQuantity: [
        { required: true, message: '请输入计划数量', trigger: 'blur' }
    ]
})

// 自动生成开关变化
const handleAutoGenerateChange = (value) => {
    if (value) {
        // 自动生成入库单号
        generateInboundCode()
    } else {
        formData.value.inboundCode = ''
    }
}

// 生成入库单号
const generateInboundCode = () => {
    const timestamp = new Date().getTime()
    const random = Math.random().toString(36).substr(2, 5)
    formData.value.inboundCode = `IN${timestamp}${random}`.toUpperCase()
}

// 仓库选项
const warehouseOptions = ref([])

let orderDialogVisible = ref(false)//计划弹窗是否显示

let plans = ref([])//计划列表

let showPlanModal = () => {
    orderDialogVisible.value = true
    request({
        url: 'report/planAll',
        method: 'get',
    }).then(res => {
        console.log(res.data)
        plans.value = res.data
    })


}//显示计划弹窗

let selectPlan = async (plan) => {
    //选择计划
    formData.value.planId = plan.planId
    formData.value.productId = plan.materialId
    formData.value.materialName = plan.materialName
    formData.value.specifications = plan.specificationsAndModels
    formData.value.unit = plan.unit
    formData.value.totalQuantity = plan.planQuantity
    orderDialogVisible.value = false

}


// 提交表单
const onSubmit = async () => {
    try {
        // 如果自动生成，确保有入库单号
        if (autoGenerate.value && !formData.value.inboundCode) {
            generateInboundCode()
        }

        // 设置创建时间
        if (!formData.value.createTime) {
            formData.value.createTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
        }

        let data ={
            inboundCode: formData.value.inboundCode,
            inboundName: formData.value.inboundName,
            planId: formData.value.planId,
            warehouseId: formData.value.warehouseId,
            totalQuantity: formData.value.totalQuantity,
            actualQuantity: formData.value.actualQuantity,
            operatorId: formData.value.operatorId,
            checkId: formData.value.checkId,
            inboundStatus: formData.value.inboundStatus,
            createTime: formData.value.createTime,
            productId: formData.value.productId,
            batchNo: formData.value.batchNo
        }

        // 调用API保存数据
        await request({
            url: '/inboundOrder/save',
            method: 'post',
            data: data
        })

        ElMessage.success('创建成功')
        emits("ref-table")
    } catch (error) {
        console.error('创建失败:', error)
        ElMessage.error('创建失败')
    }
}

// 重置表单
const resetForm = () => {
    formData.value = {
    }

    if (autoGenerate.value) {
        generateInboundCode()
    }
}

// 取消
const cancel = () => {
    emits("ref-table")
}

// 初始化时生成入库单号
generateInboundCode()
</script>

<style scoped>
.card-header {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}

.code-input-container {
    display: flex;
    align-items: center;
    gap: 10px;
}

.switch-container {
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
}

.switch-label {
    font-size: 12px;
    color: #606266;
}

.form-actions {
    text-align: center;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.el-row {
    margin-bottom: 20px;
}

.el-form-item {
    margin-bottom: 0;
}

@media (max-width: 768px) {
    .code-input-container {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .form-actions {
        text-align: center;
    }

    .form-actions .el-button {
        width: 100%;
        margin-bottom: 10px;
    }
}
</style>